#define _GNU_SOURCE
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <inttypes.h>
#include <linux/if_link.h>
#include <netdb.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <openssl/hmac.h>
#include <cjson/cJSON.h>
#include "curl_req.h"

extern int get_bindwith(const char *id, int press);
extern int get_status(const char *id);
void scan(const char *id, const char *sn, int cdn_up, int cdn_limit)
{
	printf("**************scan %s**************\n", id);
	int online = get_status(id);
	int bw = get_bindwith(id, 1);
	if (online) {
		if (bw != cdn_up) {
			printf("ONLINE BW ERROR:id=%s sn=%s cdn_up=%d bw=%d\n", id, sn, cdn_up, bw);
		}
	} else {
		printf("OFFLINE DEV id=%s sn=%s\n", id, sn);
		if (bw != cdn_up) {
			printf("OFFLINE BW ERROR:id=%s sn=%s cdn_up=%d bw=%d\n", id, sn, cdn_up, bw);
		}
	}
	return;
}

int main()
{
	FILE *fp = fopen("dev.txt", "r+");
	if (fp == NULL) {
		perror("fopen");
		exit(0);
	}

	char cdn[8][64];
	char line[1024];
	while (fgets(line, sizeof(line), fp)) {
		printf("line=%s\n", line);
		char *ptr = line;
		char *tok;
		int idx = 0;
		while ((tok = strsep(&ptr, "\t\n"))) {
			//printf("tok=%s\n", tok);
			snprintf(cdn[idx++], sizeof(cdn[1]), "%s", tok);
		}
		ptr = cdn[1];
		ptr = ptr + strlen(ptr) - 3;
		uint32_t rd = strtol(ptr, NULL, 16) >> 3;
		printf("idx=%d seq=%d id=%s sn=%s cdn_up=%d limit_bw=%d prd=%s rd=%u\n", idx, atoi(cdn[0]), cdn[2], cdn[1], atoi(cdn[3]), atoi(cdn[4]), ptr, rd);

		// if (idx == 6 && strlen(cdn[2]) > 16) {
		// 	scan(cdn[2], cdn[1], atoi(cdn[3]), atoi(cdn[4]));
		// 	sleep(1);
		// } else {
		// 	printf("ERR NODE:id=%s sn=%s cdn_up=%s bw=%s\n", cdn[2], cdn[1], cdn[3], cdn[4]);
		// }
	}
	return 0;
}